import re
from .get_jigouma import get_jigou,get_jigou2
import datetime
import time
import ddddocr
from selenium.webdriver.support import expected_conditions as ec
from mylib.main import CustomBrowser
from selenium.webdriver.common.by import By
from selenium.webdriver.support.wait import WebDriverWait

def login(driver):
    with open("./文档/admin.txt", 'r', encoding='utf-8') as file:
        content = file.readlines()

    my_list = []
    for content in content:
        my_list.append(content)

    urls = my_list[0]
    account = my_list[1].strip()
    password = my_list[2].strip()
    name = my_list[3].strip()

    driver.get(urls)

    driver.maximize_window()

    time.sleep(1.5)
    try:
        driver.switch_to.alert.accept()
    except:
        pass

    try:
        driver.switch_to.alert.accept()
    except:
        pass
    try:
        time.sleep(1)
        WebDriverWait(driver, 5).until(ec.visibility_of_element_located((By.XPATH, '//*[@id="verifyCode"]')))
        print("有验证码")
        cookies = yes_verify_code(driver, account, password)
        return cookies
    except Exception as e:
        print("没有验证码")
        domain,cookies,jigouma = no_verifyCode(driver, account, password, name)
    return domain,cookies,jigouma


def yes_verify_code(driver, account, password):

    while True:
        WebDriverWait(driver, 10).until(ec.visibility_of_element_located((By.XPATH, '//*[@id="phisname"]'))).clear()
        WebDriverWait(driver, 10).until(
            ec.visibility_of_element_located((By.XPATH, '//*[@id="phisname"]'))).send_keys(account)
        time.sleep(1)
        try:
            driver.switch_to.alert.accept()
        except:
            print('没有弹窗')


        WebDriverWait(driver, 10).until(ec.visibility_of_element_located((By.XPATH, '//*[@id="password"]'))).clear()
        WebDriverWait(driver, 10).until(
            ec.visibility_of_element_located((By.XPATH, '//*[@id="password"]'))).send_keys(password)
        time.sleep(1)

        captcha_element = driver.find_element("id", "img")
        captcha_element.screenshot("captcha.png")


        ocr = ddddocr.DdddOcr()
        with open('./captcha.png', 'rb') as f:
            img_bytes = f.read()
        res = ocr.classification(img_bytes)
        WebDriverWait(driver, 10).until(ec.visibility_of_element_located(
            (By.XPATH, '//*[@id="verifyCode"]'))).clear()
        WebDriverWait(driver, 10).until(ec.visibility_of_element_located(
            (By.XPATH, '//*[@id="verifyCode"]'))).send_keys(res)
        time.sleep(1)
        WebDriverWait(driver, 10).until(ec.visibility_of_element_located(
            (By.XPATH, '//*[@id="submitBtn"]'))).click()
        print("-------------------------------------------------")
        try:
            WebDriverWait(driver, 3).until(ec.visibility_of_element_located(
                (By.XPATH, '//span[text()="健康档案"]')))
            break
        except:
            pass

    curent_url = driver.current_url

    domain_one = re.findall('(.*?)/phis/', curent_url)[0]
    cookies_one = driver.get_cookies()
    cookies_one = cookies_one[0]['value']

    jigouma = get_jigou2(domain_one,cookies_one)
    """
    二者共用部分
    """
    print("进入到了页面")
    time.sleep(2)
    WebDriverWait(driver, 10).until(ec.visibility_of_element_located(
        (By.XPATH, '//span[text()="健康档案"]'))).click()
    print("点击健康档案")

    try:
        WebDriverWait(driver, 5).until(
            ec.visibility_of_element_located((By.XPATH, '//*[@id="button-1005-btnIconEl"]'))).click()
    except Exception as e:
        try:
            WebDriverWait(driver, 5).until(
                ec.visibility_of_element_located((By.XPATH, '//*[@id="button-1005-btnIconEl"]'))).click()
        except:
            print('弹窗异常，未加载出来', e)
            pass
    cookies = driver.get_cookies()
    current_url = driver.current_url
    domain = re.findall('(.*?)/phis/app/ehr/index', current_url)[0]
    if cookies:
        return domain, cookies, jigouma


def no_verifyCode(driver, account, password, name):
    print("+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++==")

    WebDriverWait(driver, 10).until(ec.visibility_of_element_located((By.ID, "j_username"))).send_keys(account)
    time.sleep(.5)

    WebDriverWait(driver, 10).until(ec.visibility_of_element_located((By.ID, "j_password"))).send_keys(password)
    time.sleep(.5)
    try:
        WebDriverWait(driver, 3).until(ec.visibility_of_element_located((By.CLASS_NAME, "submit-btn"))).click()
    except:
        print('无需点击登录')
    time.sleep(.5)
    try:
        WebDriverWait(driver, 10).until(ec.presence_of_element_located(
            (By.XPATH, f'//div[contains(text(), "{name}")]'))).click()
    except:
        pass

    print('进入科室')
    try:
        driver.switch_to.alert.accept()
        driver.switch_to.alert.accept()
    except:
        pass
    current_url = driver.current_url
    domain_one = re.findall('(.*?)/cis/', current_url)[0]
    cookies_one = driver.get_cookies()
    cookies_one = cookies_one[0]['value']

    jigouma = get_jigou(domain_one,cookies_one)
    print("jigouma:",jigouma)

    WebDriverWait(driver, 10).until(
        ec.visibility_of_element_located((By.XPATH, '//*[@id="dd65-ddheader"]'))).click()
    driver.close()
    time.sleep(1)
    handles = driver.window_handles
    latest_handle = handles[-1]
    driver.switch_to.window(latest_handle)
    try:
        WebDriverWait(driver, 5).until(
            ec.visibility_of_element_located((By.XPATH, '//*[@id="button-1005-btnIconEl"]'))).click()
    except Exception as e:
        pass
    cookies = driver.get_cookies()

    current_url = driver.current_url
    domain = re.findall('(.*?)/phis/app', current_url)[0]
    if cookies:
        return domain, cookies,jigouma








def get_cookies():
    driver = CustomBrowser()
    domain,cookies,jigouma = login(driver)
    cookie = cookies[0]['value']
    domain = domain
    driver.quit()
    print("domain:", domain, "cookie:", cookie,"jigouma:",jigouma)
    return domain, cookie,jigouma
if __name__ == '__main__':
    cookie = get_cookies()
    print(cookie)